package com.whsxt.service.impl;

import com.sun.org.apache.bcel.internal.classfile.Code;
import com.whsxt.common.CodeMsg;
import com.whsxt.common.Constant;
import com.whsxt.common.PageInfo;
import com.whsxt.common.Result;
import com.whsxt.dao.UserDao;
import com.whsxt.pojo.User;
import com.whsxt.service.UserService;

import java.util.List;
import java.util.Map;

/**
 * @Author 武汉尚学堂
 */
public class UserServiceImpl implements UserService {
    UserDao userDao = new UserDao();


    @Override
    public Result login(String username, String password) {
        //根据用户名和密码查询用户
        User user = userDao.selectUserByNameAndPassword(username, password);
        if (user == null){
            return new Result(CodeMsg.USERNAME_PASSWORD_ERROR);
        }
        //判断数据状态
        if (user.getDeleted().equals(Constant.INVALID)){
            return  new Result(CodeMsg.USER_DELETED_ERROR);
        }

        return new Result(user);
    }


    @Override
    public Result queryPage(Map<String, String> params, String page, String limit) {
        PageInfo<User> userPage =  userDao.selectPage(params,page,limit);
        return new Result(userPage);
    }


    @Override
    public Result addUser(String username, String realname, String role) {
        /**
         * 业务数据校验
         *  用户名是唯一的
         *  校验 这个用户名是否被占用  根据用户名查询用户
         */
        User user = userDao.selectUserByName(username);
        if (user != null){//说明用户名 已经被占用
            return  new Result(CodeMsg.USERNAME_EXIST_ERROR);
        }
        userDao.insert(username,Constant.DEFAULT_PASSWORD,realname,role);
        return new Result();
    }


    @Override
    public Result resetPassword(String id) {
        //根据ID 修改密码
        userDao.updatePassword(id,Constant.DEFAULT_PASSWORD);
        return new Result();
    }


    @Override
    public Result delete(String id) {
        //根据ID 修改状态
        userDao.delete(id,Constant.INVALID);
        return new Result();
    }


    @Override
    public Result queryAllSalesman() {
        List<User> users = userDao.selectAllSalesman();
        return new Result(users);
    }


    @Override
    public Result updatePassword(Integer id, String password) {
        userDao.updatePassword(id.toString(),password);
        return new Result();
    }

    @Override
    public Result updateImg(Integer id, String url) {
        userDao.updateImg(id,url);
        return new Result(url);
    }
}
